<template>
  <div class="search">
    <div>
      <a-spin :spinning="false">
        <a-steps :current="current" :style="{ marginBottom: '28px' }" size="small">
          <a-step title="选择分类"/>
          <a-step title="基本信息"/>
          <a-step title="商品描述"/>
          <a-step title="参数规格"/>
        </a-steps>
      </a-spin>
    </div>
    <f-form ref="form" :action="api.product" :form-key="this.formItem.productId">
      <div v-show="current==0">
        <f-form-item label="商品分类" type="other">
          <a-cascader placeholder="请选择分类" v-decorator="decorator" :options="cascaderData" @change="onChange"
                      changeOnSelect/>
        </f-form-item>
      </div>
      <div v-show="current==1">
        <f-form-item label="商品分类" type="other">
          <span v-for="(item,index) in selectData">
            {{item.categoryName}}{{index < (selectData.length-1) ? '/' : ''}}
          </span>
          <a-button type="primary" @click="pre" style="margin-left: 10px" size="small">切换分类</a-button>
        </f-form-item>
        <f-form-item label="商品名称" name="productName" :required="true" :value="formItem.productName"/>
        <f-form-item label="品牌" name="brandName" :required="true" :value="formItem.brandName"/>
        <f-form-item label="商品编号" name="productNo" :required="true" :value="formItem.productNo"/>
        <f-form-item label="货期" type="other">
          <a-input-number id="inputNumber" :min="1" v-model="formItem.deliveryTime"/>
        </f-form-item>
      </div>
      <div v-show="current==2">
        <f-form-item label="商品简介" name="productDesc" type="editor" :value="formItem"/>
        <f-form-item label="商品封面图" type="upload" name="coverImage" v-if="loaded" :value.sync="formItem.coverImage"
                     :file-max="1"/>
      </div>
      <div v-show="current==3">
        <a-divider orientation="left" width="550">商品参数</a-divider>
        <div class="table">
          <a-row class="table_header" style="padding-left: 90px;padding-top: 10px">
            <a-col span="8">
              参数名称
            </a-col>
            <a-col span="10">
              参数值
            </a-col>
          </a-row>
          <template v-for="(item,index) in commonTemplate">
            <div class="table_header2">
              <a-input size="small" placeholder="分组名称" v-model="item.group" :disabled="!item.allowDel"
                       style="padding-top:2px;width: 90px;" @on-change="(event) => changeGroup(event,item)"/>
            </div>
            <div class="table_body" style="padding-left: 180px">
              <a-row class="table_tr" v-for="(opt,index) in item.params">
                <a-col span="5" style="text-align: left">
                  <a-input placeholder="填写参数名称" v-model="opt.k" style="width: 90px;" :disabled="!opt.allowDel"/>
                </a-col>
                <a-col span="12" v-if="!opt.options||!opt.options.length">
                  <a-input :placeholder="'填写'+opt.k" v-model="opt.v"/>
                  <a-icon type="md-close-circle" class="close" title="删除" @click="delGroupItem(item,opt,index)"
                          v-if="opt.allowDel"/>
                </a-col>

                <a-col span="12" v-if="opt.options&&opt.options.length">
                  <a-select v-model="opt.selected" multiple>
                    <a-select-option v-for="o in opt.options" :value="o.name" :key="o.name">{{ o.name }}
                    </a-select-option>
                  </a-select>
                  <a-icon type="md-close-circle" class="close" title="删除" @click="delGroupItem(item,opt,index)"
                          v-if="opt.allowDel"/>
                </a-col>

                <a-col v-if="index===item.params.length-1&&item.allowDel" span="6" style="right: 0px;">
                  <Icon type="ios-trash-outline" @click="delGroup(item,index)" size="20" title="删除参数组"/>
                </a-col>

              </a-row>
            </div>
          </template>
        </div>

        <p class="btn" style="padding-top: 10px">
          <a-button type="dashed" style="width: 100%" @click="addGroupItem(commonTemplate[0])" icon="ios-add">
            添加参数
          </a-button>
        </p>

        <a-divider orientation="left">商品规格<span style="font-size: 14px;color: #b7b7b5">(制定不同商品规格,制定后客户可根据不同商品规格选择对应规格的物料)</span>
        </a-divider>
        <a-row v-for="(item,index) in specialSpecs" style="margin-bottom: 5px;">
          <a-row class="skuitem">
            <a-row>
              <a-input :placeholder="item.k" v-model="item.k" :disabled="!item.allowDel" clearable style="width: 150px;"
                       @on-change="(event) => skuItemKChange(event,item)"/>
            </a-row>
            <a-row style="padding-top: 5px;padding-bottom: 5px;">
              <a-col span="5" :name="item.k" v-for="(opt,index) in item.selected"
                     style="height:30px;padding-top: 3px;margin-bottom: 10px;">
                <a-dropdown placement="bottomLeft" @on-click="(name)=>dropdownClick(name,opt)" :trigger="['click']">
                  <a-input v-model="opt.name" style="width: 150px;font-size: 12px">
                    <f-color-picker slot="addonBefore" v-model="opt.value"
                                    @change="(color)=>headleChangeColor(color,opt)"
                                    v-if="item.type==1"></f-color-picker>
                    <a-icon type="close" slot="addonAfter" :style="{ fontSize: '10px', color: '#333' }"
                            @click="removeOption(index,item.selected)"/>
                  </a-input>
                  <a-menu slot="overlay">
                    <a-menu-item style="width: 120px;"
                                 v-if="item.options&&item.options[0].name&&item.type!=1">
                      <a-menu-item v-for="option in item.options" :name="option.name">{{option.name}}</a-menu-item>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </a-col>
              <a-button icon="ios-add" type="dashed" style="margin-top: 5px;" @click="addOption(item.selected)">
                添加{{item.k}}
              </a-button>
            </a-row>
            <a-icon type="delete" size="22" @click="removeSku(item,index)" v-if="item.allowDel"/>
          </a-row>
        </a-row>

        <a-row>
          <p>
            <a-button type="dashed" style="width: 100%" @click="addSku">添加规格</a-button>
          </p>
        </a-row>

        <a-divider orientation="left" style="width: 95%">规格列表<span style="font-size: 14px;color: #b7b7b5">(为匹配项目，价格、数量、编号，必填</span>
        </a-divider>

        <div style="padding-bottom: 5px;">
          <a-table :columns="headers" :dataSource="product.skus" style="width: 100%;">
            <template slot-scope="{ row, index }" slot="price">
              <div class="subCol">
                <a-input placeholder="请输入价格" size="small" v-model="row.price"/>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="num">
              <div class="subCol">
                <a-input placeholder="请输入数量" size="small" v-model="row.num"/>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="productNo">
              <div class="subCol">
                <a-input placeholder="请输入编号" size="small" v-model="row.productNo"/>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="images">
              <div class="subCol" style="margin-top: 5px;">
                <upload-images @change="(fileUrl,fileIds,files)=>uploadSuccess(row,fileIds,index,fileUrl,files)"
                               :fileSize="6144" :file-max="1" :size="40" :delIconSize="16" :default-list="row.images"
                               :shop-tip="false"></upload-images>
              </div>
            </template>
          </a-table>
        </div>
      </div>

    </f-form>
  </div>
</template>

<script>
  import { listToTree2 } from '@/utils/util'
  import ARow from 'ant-design-vue/es/grid/Row'
  import ACol from 'ant-design-vue/es/grid/Col'

  export default {
    name: 'productForm',
    props: {},
    data() {
      return {
        isAdd: true,
        loaded: false,
        formItem: this.getFormItem(),
        current: 0,
        isEdit: false,
        cascaderData: [],
        selectData: [],
        specialSpecs: [],
        specificationsMap: new Map(),
        commonTemplate: [],//公共规格参数模板
        skus: [],
        product: {
          categoryId1: '',
          categoryId2: '',
          productName: '',
          productPrice: 0,
          brandName: '',
          coverImage: '',
          productNo: '',
          productDesc: '',
          productSeries: '',
          visibleType: 1,
          proImgLists: [],
          skus: [],
          onLineState: 1,
          visibleConfig: [],
          domestic: '',
          place: '',
          firerating: '',
          deliveryTime: 0,
          allSpec: '',
          privateSpec: ''
        },
        columns: [{
          title: '价格',
          align: 'center',
          children: [
            {
              title: '价格',
              dataIndex:'price',
              slot: 'price',
              align: 'center',
              render: (h, params) => {
                let me = this
                let priceObj = me.skus[params.index]
                return h('div', [
                  h('InputNumber', {
                    props: {
                      type: 'text',
                      size: 'small',
                      value: priceObj ? priceObj.price : 0
                    },
                    on: {
                      'on-blur': (event) => {
                        me.skus[params.index].price = event.target.value
                      }
                    },
                    style: {
                      width: '70px'
                    }
                  })
                ])
              },
              renderHeader: (h, params) => {
                let me = this
                return h('div', [
                  h('InputNumber', {
                    props: {
                      'size': 'small',
                      'min': 0,
                      'value': 0,
                      'placeholder': '批量设置'
                    },
                    'on': {
                      'on-change': (value) => {
                        for (let i = 0; i < me.skus.length; i++) {
                          if (me.isEdit) {
                            me.skus[i].price = value
                          } else {
                            me.skus[i].price = value
                          }
                        }
                      }
                    }
                  })
                ])
              }
            }
          ]
        }, {
          title: '数量',
          align: 'center',
          children: [
            {
              slot: 'num',
              dataIndex:'num',
              align: 'center',
              render: (h, params) => {
                let me = this
                let numObj = me.skus[params.index]
                return h('div', [
                  h('InputNumber', {
                    props: {
                      type: 'text',
                      size: 'small',

                      value: numObj ? numObj.num : 0
                    },
                    on: {
                      'on-blur': (value) => {
                        me.skus[params.index].num = value
                      }
                    },
                    style: {
                      width: '60px'
                    }
                  })
                ])
              },
              renderHeader: (h, params) => {
                let me = this
                return h('div', [
                  h('InputNumber', {
                    props: {
                      'size': 'small',
                      'min': 0,
                      'value': 0,
                      'placeholder': '批量设置'
                    },
                    'on': {
                      'on-change': (value) => {
                        for (let i = 0; i < me.skus.length; i++) {
                          if (me.isEdit) {
                            me.skus[i].num = value
                          } else {
                            me.skus[i].num = value
                          }
                        }
                      }
                    }
                  })
                ])
              }
            }
          ]
        },
          {
            title: '编号',
            align: 'center',
            children: [
              {
                slot: 'productNo',
                dataIndex:'productNo',
                align: 'center',
                render: (h, params) => {
                  let me = this
                  let productNoObj = me.skus[params.index]
                  return h('div', [
                    h('Input', {
                      props: {
                        type: 'text',
                        size: 'small',
                        value: productNoObj ? productNoObj.productNo : 0
                      },
                      on: {
                        'on-blur': (event) => {
                          me.skus[params.index].productNo = event.target.value
                        }
                      },
                      style: {
                        width: '60px'
                      }
                    })
                  ])
                },
                renderHeader: (h, params) => {
                  let me = this
                  return h('div', [
                    h('Input', {
                      props: {
                        'size': 'small',
                        'placeholder': '批量设置'
                      },
                      'on': {
                        'on-change': () => {
                          for (let i = 0; i < me.skus.length; i++) {
                            if (me.isEdit) {
                              me.skus[i].productNo = event.target.value
                            } else {
                              me.skus[i].productNo = event.target.value
                            }
                          }
                        }
                      }
                    })
                  ])
                }
              }
            ]
          },
          {
            title: '规格图片',
            slot: 'images',
            width: 250,
            align: 'center'
          }
        ]
      }
    },
    computed: {
      decorator: function() {
        let obj = [this.categoryName]
        let config = {}
        //config.initialValue = this.value
        obj.push(config)
        return obj
      },
      getData: function() {
        return this.$moment().format()
      },
      headers() {
        console.log('计算表头开始')
        const headers = []
        //商品规格表头
        const skuColumns = []
        //公共表头
        const commonColumns = ['price', 'num', 'productNo', 'images', 'imageIds', 'skuId', 'indexes']
        //遍历skus获取表头
        if (this.skus.length > 0) {
          Object.keys(this.skus[0]).forEach(k => {
            if (!commonColumns.includes(k)) {
              skuColumns.push({
                title: k,
                key: k,
                width: 100,
                align: 'center'
              })
            }
          })
          let sku = {
            title: '商品规格',
            key: 'sku',
            align: 'center',
            children: []
          }
          sku.children = skuColumns
          headers.push(sku, ...this.columns)
        }
        console.log('计算表头结束')
        return headers
      }
    },
    methods: {
      getFormItem() {
        return {
          productName: '',
          brandName: '',
          productNo: '',
          deliveryTime: 0,
          productDesc: '',
          coverImage: ''
        }
      },
      setData(data) {
        this.$refs.form.resetFields()
        this.formItem = this.getFormItem()
        this.isAdd = true
        if (data && data.productId) {
          this.formItem = data
          this.isAdd = false
        }
        this.loaded = true
      },
      handleSubmit() {
        this.$refs.form.submit({
          companyLogo: this.formItem.companyLogo,
          companyDesc: this.formItem.companyDesc,
          businessScope: this.formItem.businessScope
        })
      },
      pre() {
        if (this.current > 0) {
          this.current--
        }
        return this.current
      },
      next() {
        if (this.current == 0) {
          if (this.selectData.length <= 0) {
            this.$message.error('请选择商品分类')
          }
        }
        if (this.current < 3) {
          this.current++
        }
        return this.current
      },
      getCategory() {
        this.http.get(this, {
          url: this.api.category.list,
          data: {
            params: {}
          },
          success: function(me, data) {
            let obj = listToTree2(data, {
              primaryKey: 'categoryId',
              titleKey: 'categoryName'
            })
            me.cascaderData = obj
          }
        })
      },
      onChange(value, opt) {
        let selectData = opt
        this.selectData = selectData
        for (let i in selectData) {
          let category = selectData[i]
          let index = parseInt(i) + 1
          let categoryId = category.categoryId
          this.formItem['category' + index] = categoryId
          if (i = selectData.length - 1) {
            console.log(categoryId)
            this.getSpecifications(categoryId)
          }
        }

      },
      //填写参数项
      addGroupItem(item) {
        this.allSpecs.forEach((value) => {
          if (value.id == item.id) {
            value.params.push({
              'id': new Date().getTime(),
              'k': '',
              'searchable': true,
              'type': 2,
              'allowDel': true,
              'sku': false,
              'selected': [],
              'numerical': true,
              'unit': '',
              'v': ''
            })
          }
        })
        this.dataProces(this.allSpecs)
      },
      //删除参数项,因为存在规格项所以需要对比参数名确定索引位置
      delGroupItem(item, opt, index) {
        this.allSpecs.forEach(({ id, params }) => {
          if (id == item.id) {
            params.forEach(({ id }, index) => {
              if (opt.id == id) {
                params.splice(index, 1)
              }
            })
          }
        })
        this.dataProces(this.allSpecs)
      },
      //删除参数组
      delGroup(item) {
        this.allSpecs.forEach(({ id }, index) => {
          if (id == item.id) {
            this.allSpecs.splice(index, 1)
          }
        })
        this.dataProces(this.allSpecs)
      },
      //参数组输入框修改
      changeGroup(event, item) {
        this.allSpecs.forEach((value, index) => {
          if (value.id == item.id) {
            value.group = item.group
          }
        })
      },
      //删除参数项,因为存在规格项所以需要对比参数名确定索引位置
      delGroupItem(item, opt, index) {
        this.allSpecs.forEach(({ id, params }) => {
          if (id == item.id) {
            params.forEach(({ id }, index) => {
              if (opt.id == id) {
                params.splice(index, 1)
              }
            })
          }
        })
        this.dataProces(this.allSpecs)
      },
      //查询商品规格参数模板
      getSpecifications(categoryId) {
        if (categoryId && categoryId != '') {
          this.http.get(this, {
            url: this.api.specscategory.getSpecsCategory,
            params: {
              categoryId: categoryId
            },
            success: function(me, data) {
              console.log(data)
              let result = JSON.parse(data.specifications)
              me.allSpecs = result
              //处理默认选项,从参数模板中读取
              me.allSpecs.forEach(({ params }) => {
                params.forEach((item, index) => {
                  me.specificationsMap.set(item.k, item.options)
                })
              })
              console.log(me.specificationsMap)
              me.dataProces(me.allSpecs)
            }
          })
        }
      },
      //新增商品时数据处理
      dataProces(temp) {
        let commonTemplate = []
        let specialTemplate = []
        let count = 0
        let me = this
        temp.forEach(({ params }) => {
          params.forEach((item, index) => {
            if (!item.selected) {
              item.selected = []
            }
            //取值规格模板中选项
            item.options = me.specificationsMap.get(item.k)
            if (!item.options) {
              item.options = []
            }
            if (item.sku) {
              specialTemplate.push({
                id: item.id,
                k: item.k,
                options: item.options,
                type: item.type,
                allowDel: item.allowDel,
                selected: item.selected
              })
            }
          })
        })
        //公共参数可能有多组,需单独处理
        for (let i = 0; i < temp.length; i++) {
          if (temp[i].params.length > 0) {
            let temp2 = temp[i].params
            let param = []
            for (let j = 0; j < temp2.length; j++) {
              if (!temp2[j].sku) {
                param.push(temp2[j])
              }
            }
            if (count !== temp2.length && param.length !== 0) {
              commonTemplate.push({
                id: temp[i].id,
                group: temp[i].group,
                allowDel: temp[i].allowDel,
                params: param
              })
            }
          }
        }
        console.log('公共参数', commonTemplate)
        console.log('私有参数', specialTemplate)
        this.specialSpecs = specialTemplate
        this.commonTemplate = commonTemplate
      },
      //规格
      skuItemKChange(event, item) {
        this.allSpecs.forEach(({ id, params }) => {
          params.forEach(({ id }, index) => {
            if (item.id == id) {
              params[index].k = item.k
            }
          })
        })
      },
      //删除规格项
      removeSku(item, index) {
        this.allSpecs.forEach(({ params }, i) => {
          params.forEach(({ id }, i) => {
            if (item.id == id) {
              params.splice(i, 1)
            }
          })
        })
        this.specialSpecs.splice(index, 1)
      },
      //添加规格值
      addOption(selected) {
        console.log(selected)
        if (selected) {
          selected.push({ name: '规格值', value: '' })
        }
        console.log(this.product.skus)
      },
      //删除规格值
      removeOption(index, option) {
        option.splice(index, 1)
      },
      dropdownClick(name, opt) {
        opt.name = name
      },
      //颜色选择器点击事件
      headleChangeColor(color, item) {
        console.log(item)
        item.name = color.label
      },
      //添加规格项
      addSku() {
        if (this.specialSpecs.length >= 5) {
          this.$message.info('规格最大为5项')
          return
        }
        let sku = {
          id: new Date().getTime(),
          k: '规格名称',
          type: 2,
          allowDel: true,
          sku: true,
          selected: [{ name: '规格值', value: '' }]
        }
        this.allSpecs[0].params.push(sku)
        this.specialSpecs.push(sku)
      },
      //删除规格项
      removeSku(item, index) {
        this.allSpecs.forEach(({ params }, i) => {
          params.forEach(({ id }, i) => {
            if (item.id == id) {
              params.splice(i, 1)
            }
          })
        })
        this.specialSpecs.splice(index, 1)
      }
    },
    created() {
      this.getCategory()
    },
    watch: {},
    components: { ACol, ARow }
  }
</script>

<style scoped lang="less" rel="stylesheet/less">
  .skuitem {
    border: 1px dashed #ddd;
    padding: 10px;
  }

  .table_header {
    background-color: #f5f4f4;
    text-align: center;
    font-size: 13px;
    border-bottom: 1px solid #eeeeee;
    font-weight: bold;
    padding: 5px 10px 5px 1px;
  }

  .table_header2 {
    background-color: #f5f4f4;
    text-align: left;

    color: #FF005D;
    height: 30px;
    font-size: 13px;
    padding-left: 30px;

    i {
      font-size: 22px;
      margin-top: 4px;
      margin-right: 10px;
    }
  }
</style>
